package com.traffic.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.constant.Const;
import com.traffic.constant.Status;
import com.traffic.entity.Sms;
import com.traffic.exception.BaseException;
import com.traffic.mapper.SmsMapper;
import com.traffic.model.ApiResponse;
import com.traffic.model.SmsResult;
import com.traffic.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;
//如果JDK版本是1.8,可使用原生Base64类


/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/13
 */
@Service
@Slf4j
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements SmsService {

    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    //必填,请参考"开发准备"获取如下数据,替换为实际值
    String url = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1"; //APP接入地址+接口访问URI
    String appKey = "Id4Id9t573hd9Caw6r3eNqtSIDmK"; //APP_Key
    String appSecret = "J1Jz9M060QKBhcdSYYfjh84Bd2md"; //APP_Secret
    String sender = "8820120123783"; //国内短信签名通道号或国际/港澳台短信通道号
    String templateId = "2258f0c94e28486ebcf1a1596afc721e"; //模板ID

    @Autowired
    private SmsMapper smsMapper;

    /**
     * 发送短信验证码
     * @param phone 用户的手机号
     * @return
     */
    @Override
    public ApiResponse sendSms(String phone) {
        log.info("【短信发送流程开始】");
        QueryWrapper<Sms> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        wrapper.eq("status", Const.SMS_TODAY);
        Sms sms = smsMapper.selectOne(wrapper);
        // 数据库中有该手机号的发送记录
        // 检查是否满足再次发送条件
        if (ObjectUtil.isNotNull(sms)) {
            // 次数检查
            if (sms.getRequestTimes() >= Const.SMS_MAX_TIMES) {
                return ApiResponse.ofStatus(Status.SMS_TIMES_ERROR);
            }
            // 时间检查
            Long now = System.currentTimeMillis();
            Long old = sms.getLastRequestTime();
            if (now - old <= Const.SMS_WAIT) {
                return ApiResponse.ofStatus(Status.SMS_WAIT_ERROR);
            }
        }
        // 请求发送验证码接口
        //条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
        //国际/港澳台短信不用关注该参数
        String signature = "高骐科技"; //签名名称

        //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
        String receiver = "+86" + phone; //短信接收人号码

        //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
        String statusCallBack = "";

        /**
         * 选填,使用无变量模板时请赋空值 String templateParas = "";
         * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
         * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
         * 模板中的每个变量都必须赋值，且取值不能为空
         * 查看更多模板和变量规范:产品介绍>模板和变量规范
         */
        String code = RandomUtil.randomNumbers(Const.SMS_CODE_LENGTH).toString();
        String templateParas = "[\"" + code + "\"]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）

        log.info("【短信接收号码】:{}", phone);
        log.info("【短信验证码】:{}", code);

        //请求Body,不携带签名名称时,signature请填null
        String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            log.error("body is null.");
            throw new BaseException(Status.COMMON_ERROR);
        }

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            log.error("wsse header is null.");
            throw new BaseException(Status.COMMON_ERROR);
        }

        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();

            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                    .setUri(url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());

            String resultBody = EntityUtils.toString(response.getEntity());
            log.info("【响应头域信息】:{}", response.toString()); //打印响应头域信息
            log.info("【响应消息实体】:{}", body); //打印响应消息实体

            // todo 发送成功后
            log.info("【请求状态码】:{}", response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200) {
                SmsResult smsResult = new SmsResult();
                try {
                    smsResult = JSON.parseObject(resultBody, SmsResult.class);
                    log.info("【返回数据状态码】:{}", smsResult.getCode());
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("JSON转化失败");
                }

                if (StrUtil.equals(smsResult.getCode(), Const.SMS_OK)) {
                    // 发送成功
                    // 已有记录 更新
                    if (ObjectUtil.isNotNull(sms)) {
                        sms.setRequestTimes(sms.getRequestTimes() + 1);
                        sms.setLastRequestTime(System.currentTimeMillis());
                        sms.setCode(code);
                        smsMapper.updateById(sms);
                    }else {
                        // 没有记录 添加
                        Sms newSms = Sms.builder()
                                .code(code)
                                .requestTimes(Const.SMS_ONE)
                                .phone(phone)
                                .lastRequestTime(System.currentTimeMillis())
                                .status(Const.SMS_TODAY)
                                .build();
                        smsMapper.insert(newSms);
                    }
                    log.info("【短信发送成功】");
                    return ApiResponse.ofStatus(Status.OK);
                }
                // 请求接口成功 返回结果是失败
                return ApiResponse.ofStatus(Status.COMMON_ERROR);
            }else {
                // 请求接口失败
                throw new BaseException(Status.COMMON_ERROR);
            }
        }catch (Exception e) {
            // 其他错误
            throw new BaseException(Status.UNKNOWN_ERROR);
        }

    }


    /**
     * 短信验证码 验证
     * @param phone
     * @param code
     * @return
     */
    @Override
    public ApiResponse check(String phone, String code) {
        QueryWrapper<Sms> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        wrapper.eq("status", Const.SMS_TODAY);
        Sms sms = smsMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(sms)) {
            Long now = System.currentTimeMillis(); //毫秒
            Long old = sms.getLastRequestTime();
            // 有效时间判断
            if (now - old > Const.SMS_KEEP_TIME) {
                return ApiResponse.ofStatus(Status.SMS_CODE_MORE_TIME);
            }
            // 验证码判断
            if (StrUtil.equals(code, sms.getCode())) {
                return ApiResponse.ofStatus(Status.OK);
            }else {
                return ApiResponse.ofStatus(Status.SMS_CODE_ERROR);
            }
        }
        return ApiResponse.ofStatus(Status.SMS_CODE_ERROR);
    }


    /**
     * 构造请求Body体
     * @param sender
     * @param receiver
     * @param templateId
     * @param templateParas
     * @param statusCallbackUrl
     * @param signature | 签名名称,使用国内短信通用模板时填写
     * @return
     */
    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                   String statusCallbackUrl, String signature) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            System.out.println("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }
        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }

    /**
     * 构造X-WSSE参数值
     * @param appKey
     * @param appSecret
     * @return
     */
    static String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            log.error("buildWsseHeader(): appKey or appSecret is null.");
            throw new BaseException(Status.COMMON_ERROR);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date()); //Created
        String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
        //如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
        //String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest
        //若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正
        //passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }
}
